﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace PIM_ATE.Mods
{
    class ClsDataSetup
    {
        /// <summary>
        /// 保存交调测试产品设置信息
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 产品代码
        /// </summary>
        public string ProCode { get; set; }
        /// <summary>
        /// 关键工序
        /// </summary>
        public string KEYWP { get; set; }
        /// <summary>
        /// 校准有效时限，单位H
        /// </summary>
        public int CalTimeLimit { get; set; }
        /// <summary>
        /// 状态标识
        /// </summary>
        public string TestStep { get; set; }
        /// <summary>
        /// 过程标识
        /// </summary>
        public string ProcessStep { get; set; }
        /// <summary>
        /// 是否需要标准件校准, 是/否
        /// </summary>
        public bool IsISOCcal { get; set; }
        /// <summary>
        /// 校正开关, 是/否
        /// </summary>
        public bool IsCheckOn { get; set; }
        /// <summary>
        /// 随机数开关, 是/否
        /// </summary>
        public bool IsRandomOn { get; set; }
        /// <summary>
        /// 设置的版本
        /// </summary>
        public string SetupVer { get; set; }
        /// <summary>
        /// 有效性, 是/否
        /// </summary>
        public bool Effective { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }

        public void setValues(string sCode, DataRow drRow)
        {
            int n = 0;
            //ID = Convert.ToInt32(drRow[n++].ToString());
            ProCode = sCode.ToString();
            KEYWP = drRow[n++].ToString();
            CalTimeLimit = Convert.ToInt32(drRow[n++].ToString());
            IsISOCcal = PIMFunction.getBoolean(drRow[n++].ToString());
            TestStep = drRow[n++].ToString();
            ProcessStep = drRow[n++].ToString();
            IsCheckOn = PIMFunction.getBoolean(drRow[n++].ToString());
            IsRandomOn = PIMFunction.getBoolean(drRow[n++].ToString());
            SetupVer = drRow[n++].ToString();
            Effective = PIMFunction.getBoolean(drRow[n++].ToString());
            Remark = drRow[n++].ToString();
        }

        public string toValue()
        {
            string sValues = "";
            sValues += "'" + ProCode + "',";
            sValues += "'" + KEYWP + "',";
            sValues += "'" + CalTimeLimit + "',";
            sValues += "'" + IsISOCcal + "',";
            sValues += "'" + TestStep + "',";
            sValues += "'" + ProcessStep + "',";


            sValues += "'" + IsCheckOn + "',";
            sValues += "'" + IsRandomOn + "',";
            sValues += "'" + SetupVer + "',";
            sValues += "'" + Effective + "',";
            sValues += "'" + Remark + "'";
            return sValues;
        }
    }

    class ClsDataSetupBuilder
    {
        const string TABLE_NAME = "tb_PIMSetup";
        string m_sConnect;
        string m_sProCode;
        //DataTable m_dtData;
        List<ClsDataSetup> m_lstSetup;

        #region static function

        public static bool createDataTable()
        {
            string strSql = "CREATE TABLE \"tb_PIMSetup\" (" +
                            "\"ID\" INT NOT NULL identity(1,1) PRIMARY KEY, " +
                            "\"ProCode\" NVARCHAR(100) NOT NULL, " +
                            "\"KEYWP\" VARCHAR(50) NOT NULL, " +
                            "\"CalTimeLimit\" VARCHAR(50) NOT NULL, " +
                            "\"IsISOCcal\" NVARCHAR(10) NOT NULL, " +
                            "\"TestStep\" NVARCHAR(50), " +
                            "\"ProcessStep\" NVARCHAR(50), " +
                            "\"IsCheckOn\" NVARCHAR(10) NOT NULL, " +
                            "\"IsRandomOn\" NVARCHAR(10) NOT NULL, " +
                            "\"SetupVer\" NVARCHAR(50) NOT NULL, " +
                            "\"Effective\" NVARCHAR(10) NOT NULL, " +
                            "\"Remark\" NVARCHAR(200)" +
                            ");";
            try
            {
                MicroDBHelper.ExecuteNonQuery(strSql, null);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public static List<string> getColNames()
        {
            List<string> names = new List<string>();
            names.Add("ID");
            names.Add("ProCode");
            names.Add("KEYWP");
            names.Add("CalTimeLimit");
            names.Add("IsISOCcal");
            names.Add("TestStep");
            names.Add("ProcessStep");
            names.Add("IsCheckOn");
            names.Add("IsRandomOn");
            names.Add("SetupVer");
            names.Add("Effective");
            names.Add("Remark");
            return names;
        }

        public static List<string> getColNamesCN()
        {
            List<string> names = new List<string>();
            names.Add("ID");
            names.Add("产品代码");
            names.Add("关键工序");
            names.Add("校准时限");
            names.Add("是否需要校准件");
            names.Add("状态标识");
            names.Add("过程标识");
            names.Add("Check开关");
            names.Add("Random开关");
            names.Add("设置版本");
            names.Add("有效性");
            names.Add("备注");
            return names;
        }

        public static string getColNamesStr(int index = 2)
        {
            string[] lstCol = getColNames().ToArray();
            string sColNames = "";
            for (int i = index; i <= lstCol.Length - 1; i++)
            {
                if (i != lstCol.Length - 1)
                    sColNames += "[" + lstCol[i] + "],";
                else
                    sColNames += "[" + lstCol[i] + "]";
            }
            return sColNames;
        }

        public static string getColNamesCNStr(int index = 2)
        {
            string[] lstCol = getColNames().ToArray();
            string[] lstColCN = getColNamesCN().ToArray();
            string sColNames = "";
            for (int i = index; i <= lstCol.Length - 1; i++)
            {
                if (i != lstCol.Length - 1)
                    sColNames += "[" + lstCol[i] + "] as [" + lstColCN[i] + "],";
                else
                    sColNames += "[" + lstCol[i] + "] as [" + lstColCN[i] + "]";
            }
            return sColNames;
        }

        #endregion

        public ClsDataSetupBuilder(string alias)
        {
            m_sConnect = alias;
        }

        public void construct(string sProCode)
        {
            m_sProCode = sProCode;
        }

        public ClsDataSetup downloadVaule(ref string error_info)
        {
            DataTable dtShow = download(ref error_info);
            if (dtShow == null || error_info != "" || dtShow.Rows.Count == 0)
            {
                return null;
            }

            float fMaxVer = float.MinValue;
            int index = 0;
            for (int i = 0; i < dtShow.Rows.Count; i++)
            {
                float ver = Convert.ToSingle(dtShow.Rows[i][7]);
                if (ver > fMaxVer)
                {
                    fMaxVer = ver;
                    index = i;
                }
            }
            ClsDataSetup setup = new ClsDataSetup();
            setup.setValues(m_sProCode, dtShow.Rows[index]);
            return setup;
        }

        public List<ClsDataSetup> download(out DataTable dtShow, ref string error_info)
        {
            dtShow = null;
            dtShow = download(ref error_info);
            if (dtShow == null || error_info != "" || dtShow.Rows.Count == 0)
            {
                return null;
            }

            m_lstSetup = new List<ClsDataSetup>();
            for (int i = 0; i < dtShow.Rows.Count; i++)
            {
                ClsDataSetup setup = new ClsDataSetup();
                setup.setValues(m_sProCode, dtShow.Rows[i]);
                m_lstSetup.Add(setup);
            }

            return m_lstSetup;
        }

        public DataTable download(ref string error_info)
        {//下载当前版本的配置
            if (m_sProCode == null || m_sProCode == "")
            {//错误
                error_info = "当前实例未构造sProCode";
                return null;
            }

            //获取表头信息
            string sColNames = getColNamesCNStr();
            SqlParameter param_code = new SqlParameter("@code", m_sProCode);
            //获取数据
            string sSql = "select " + sColNames + " from " + TABLE_NAME + " where [ProCode] = @code ";
            try { return MicroDBHelper.ExecuteDataTable(sSql, new SqlParameter[] { param_code }, m_sConnect); }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return null;
            }
        }

        public bool upload(ClsDataSetup setup, ref string error_info)
        {
            try
            {
                SqlParameter param_code = new SqlParameter("@code", setup.ProCode);
                SqlParameter param_ver = new SqlParameter("@ver", setup.SetupVer);
                string sSql = "select count(*) from " + TABLE_NAME + " where [ProCode] = @code and [SetupVer] = @ver ";
                int n = (int)MicroDBHelper.ExecuteScalar(sSql, new SqlParameter[] { param_code, param_ver }, m_sConnect);
                if (n > 0)
                {
                    error_info = "版本已存在";
                    return false;
                }
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return false;
            }

            try
            {
                string sColNames = getColNamesStr(1);
                string sSql = String.Format("insert into {0} ({1}) values ({2});", TABLE_NAME, sColNames, setup.toValue());
                return MicroDBHelper.ExecuteNonQuery(sSql, null, m_sConnect) == 1;
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return false;
            }
        }

        public bool upload(DataTable dtSetup, ref string error_info)
        {
            if (m_sProCode == null || m_sProCode == "")
            {//错误
                error_info = "当前实例未构造sProCode";
                return false;
            }

            try
            {
                using (var tran = MicroDBHelper.UseTransaction(IsolationLevel.RepeatableRead, m_sConnect))
                {
                    SqlParameter param_code = new SqlParameter("@code", m_sProCode);
                    string sSql = "delete from " + TABLE_NAME + " where [ProCode] = @code;";
                    MicroDBHelper.ExecuteNonQuery(sSql, new SqlParameter[] { param_code }, tran);

                    sSql = "";
                    string sColNames = getColNamesStr(1);
                    for (int i = 0; i < dtSetup.Rows.Count; i++)
                    {
                        ClsDataSetup setup = new ClsDataSetup();
                        setup.setValues(m_sProCode, dtSetup.Rows[i]);
                        sSql += String.Format("insert into {0} ({1}) values ({2});", TABLE_NAME, sColNames, setup.toValue());
                    }
                    MicroDBHelper.ExecuteNonQuery(sSql, null, tran);
                    tran.MarkSuccess();
                }
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return false;
            }

            return true;
        }
    }

}
